<template>
  <ul class="list">
    <li class="item"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        @click="handleLetterClick">{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  // 数据更新后
  updated () {
    this.startY = this.$refs['A'][0].offsetTop // A到屏幕顶部距离
  },
  computed: {
    letters () {
      const letters = []
      // for...in 循环只遍历可枚举属性
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
      // alert('handleLetterClick')
    },
    handleTouchStart () {
      this.touchStatus = true
      // console.log('handleTouchStart')
    },
    handleTouchMove (e) {
      // 当处于拖动状态中
      // console.log('handleTouchMove')
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 79 // 触摸点相对于浏览器的 viewport上边缘的 y 坐标。不会包括上边的滚动距离 再减去header的79px
          const index = Math.floor((touchY - this.startY) / 20)
          // console.log(startY, touchY, index)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
      // console.log('handleTouchEnd')
    }
  }
}
</script>

<style lang='scss' scoped>
@import '~@sass/varibles/_color.scss';
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.58rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;
  line-height: 0.4rem;
}
.item {
  text-align: center;
  color: #00bcd4;
}
</style>
